<template>
  <div class="order-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <!-- <span>订单列表</span> -->
        <el-button style="float: right; margin-left: 10px;" type="primary" icon="el-icon-plus"
          @click="handleAdd">新增</el-button>
        <el-button style="float: right; margin-left: 10px;" type="success" icon="el-icon-setting"
          @click="handlePriceConfig">价格配置</el-button>
        <!-- 客户管理 -->
        <!-- <el-button style="float: right; margin-left: 10px;" type="primary" icon="el-icon-setting"
          @click="handleCustomerConfig">客户管理</el-button> -->
        <!-- <el-button
                    style="float: right; padding: 3px 0"
                    type="text"
                    icon="el-icon-refresh"
                    @click="getList"
                >刷新</el-button> -->
      </div>
      <!-- 搜索区域 -->
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
        <el-form-item :label="$t('orders.orderCode')" prop="orderCode">
          <el-input v-model="queryParams.orderCode" :placeholder="$t('orders.orderCode')" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <!-- <el-form-item :label="$t('orders.userName')" prop="userName">
          <el-input v-model="queryParams.userName" :placeholder="$t('orders.userName')" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item> -->
        <el-form-item :label="$t('orders.userEmail')" prop="userEmail">
          <el-input v-model="queryParams.userEmail" :placeholder="$t('orders.userEmail')" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item :label="$t('orders.cardName')" prop="cardName">
          <el-input v-model="queryParams.cardName" :placeholder="$t('orders.cardName')" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item :label="$t('orders.certificationCompany')" prop="certificationCompany">
          <el-select clearable v-model="queryParams.certificationCompany"
            :placeholder="$t('orders.certificationCompany')" size="small">
            <el-option label="PSA" value="PSA" />
            <el-option label="BGS" value="BGS" />
            <el-option label="CGC" value="CGC" />
            <el-option label="ARS" value="ARS" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('orders.trainNumber')" prop="trainNumber">
          <el-input v-model="queryParams.trainNumber" :placeholder="$t('orders.trainNumber')" clearable size="small"
            @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item :label="$t('orders.certificationStatus')" prop="certificationStatus">
          <el-select clearable v-model="queryParams.certificationStatus" :placeholder="$t('orders.certificationStatus')"
            size="small">
            <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label" :value="dict.value" />
          </el-select>
        </el-form-item>
        <!-- <el-form-item label="鉴定分数" prop="certificationScore">
                    <el-input-number
                        v-model="queryParams.certificationScore"
                        placeholder="请输入鉴定分数"
                        clearable
                        size="small"
                        :min="0"
                        :max="100"
                    />
                </el-form-item> -->
        <el-form-item :label="$t('orders.certificationNumber')" prop="certificationNumber">
          <el-input v-model="queryParams.certificationNumber" :placeholder="$t('orders.certificationNumber')" clearable
            size="small" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{ $t('common.search')
          }}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{ $t('common.reset') }}</el-button>
          <!-- 导出 -->
          <el-button type="primary" icon="el-icon-download" size="mini" @click="exportExcle">导出</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="tableData" style="width: 100%" height="calc(100vh - 400px)" border v-loading="loading"
        :header-cell-style="{
          background: '#f5f7fa',
          color: '#606266',
          fontWeight: 'bold'
        }" :row-class-name="tableRowClassName" highlight-current-row>
        <el-table-column prop="orderCode" :label="$t('orders.orderCode')" width="120" align="center">
          <template slot-scope="scope">
            <el-link type="primary" @click="handleDetail(scope.row)"> {{ scope.row.orderCode }}</el-link>
          </template>
        </el-table-column>
        <el-table-column prop="userEmail" :label="$t('orders.userEmail')" width="180" align="center" />
        <el-table-column prop="cardName" :label="$t('orders.cardName')" width="120" align="center" />
        <el-table-column prop="certificationCompany" :label="$t('orders.certificationCompany')" width="120"
          align="center" />
        <el-table-column prop="trainNumber" :label="$t('orders.trainNumber')" width="120" align="center" />
        <!-- 送鉴状态 -->
        <el-table-column prop="certificationStatus" :label="$t('orders.certificationStatus')" width="120"
          align="center">
          <template slot-scope="scope">
            <el-tag>
              {{ OrderStatusText[scope.row.certificationStatus] }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="certificationNumber" :label="$t('orders.certificationNumber')" width="120"
          align="center" />
        <el-table-column prop="psaUrl" :label="$t('orders.psaUrl')" width="180" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-link v-if="scope.row.psaUrl" type="primary" :href="scope.row.psaUrl" target="_blank" :underline="false">
              {{ scope.row.psaUrl }}
            </el-link>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column prop="certificationScore" :label="$t('orders.certificationScore')" width="100"
          align="center" />
        <el-table-column prop="cost" label="鉴定费用" width="100" align="center">
          <template slot-scope="scope">
            <span style="color: #f56c6c">{{ scope.row.cost }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="saleAmount" label="贩卖金额" width="100" align="center">
          <template slot-scope="scope">
            <span style="color: #f56c6c">{{ scope.row.saleAmount }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="costStatus" :label="$t('orders.costStatus')" width="100" align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.costStatus == 1">{{ $t('orders.addSubStatus3') }}</span>
            <span v-if="scope.row.costStatus == 2">{{ $t('orders.addSubStatus4') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="createdTime" :label="$t('common.createdTime')" width="150" align="center" />
        <el-table-column label="操作" align="center" width="440" fixed="right">
          <template slot-scope="scope">

            <!-- <el-button size="mini" type="primary" icon="el-icon-view" @click="handleDetail(scope.row)">{{
            $t('common.detail') }}</el-button> -->
            <el-button size="mini" type="warning" icon="el-icon-edit" @click="handleUpdate(scope.row)">{{
              $t('common.edit') }}</el-button>
            <el-button size="mini" type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)">{{
              $t('common.delete') }}</el-button>
            <!-- 上架商品-->
            <!-- <el-button v-hasPermi="['card:order:shelf']" size="mini" type="success" icon="el-icon-s-shop"
              @click="handleShangjia(scope.row)">上架商品</el-button> -->

            <el-button v-hasPermi="['order:chaike']" size="mini" type="info" icon="el-icon-scissors" style="margin-right: 10px;"
              @click="handleDelegatedDisassembly(scope.row)">{{ $t('orders.certificationStatus5') }}</el-button>
            <!-- 委托贩卖 -->
            <!-- <el-button v-hasPermi="['order:fanmai']" size="mini" type="success" icon="el-icon-shopping-cart-full"
              @click="handleDelegatedSell(scope.row)">{{ $t('orders.certificationStatus4') }}</el-button> -->
            <!-- 已寄回客户 -->
            <!-- <el-button v-hasPermi="['order:jihui']" size="mini" type="success" icon="el-icon-s-promotion"
              @click="handleReturnToCustomer(scope.row)">{{ $t('orders.certificationStatus3') }}</el-button> -->
            <el-dropdown size="mini" split-button type="primary" style="margin-right: 10px;">
              委托贩卖
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item @click.native="handleShangjia(scope.row)">上架挂售</el-dropdown-item>
                <el-dropdown-item @click.native="handleShangjianpai(scope.row)">上架竞拍</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>

          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
        @pagination="getList" />
    </el-card>
    <!-- 暂存抽屉 -->
    <el-drawer :title="pauseDialogTitle" :visible.sync="pauseDialogVisible" direction="rtl" size="100%"
      :close-on-click-modal="false" custom-class="add-order-drawer">
      <div style="display: flex; height: 100%;">
        <div style="width: 50%;" class="drawer-container left">
          <div class="drawer-header">
            <div class="title">{{ $t('common.basicInfo') }}</div>
          </div>
          <el-form :model="addForm" ref="addFormRef" label-width="110px" :rules="addRules"
            class="add-form add-form-grid">
            <el-row :gutter="20">
              <!-- 订单编号 -->
              <!-- <el-col :span="12">
                <el-form-item :label="$t('orders.orderCode')" prop="orderCode">
                  <el-input v-model="addForm.orderCode" :placeholder="$t('orders.orderCode')" :disabled="isEdit" />
                </el-form-item>
              </el-col> -->
              <el-col :span="12">
                <el-form-item :label="$t('orders.userEmail')" prop="userEmail">
                  <el-select clearable v-model="addForm.userEmail" :placeholder="$t('orders.userEmail')" filterable
                    allow-create default-first-option size="small">
                    <el-option v-for="item in userList" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="$t('orders.cardName')" prop="cardName">
                  <el-input v-model="addForm.cardName" :placeholder="$t('orders.cardName')" />
                </el-form-item>
              </el-col>

            </el-row>
            <el-row :gutter="10">
              <el-col :span="12">
                <el-form-item :label="$t('orders.serviceType')" prop="serviceType">
                  <el-select clearable v-model="addForm.serviceType" :placeholder="$t('orders.serviceType')"
                    @change="handleServiceOrPriceTypeChange">
                    <el-option :label="$t('orders.certificationScore')" value="1" />
                    <el-option :label="$t('orders.reCertification')" value="2" />
                    <!-- <el-option :label="$t('orders.reSeal')" value="3" /> -->
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="$t('orders.priceType')" prop="priceType">
                  <el-select clearable v-model="addForm.priceType" :placeholder="$t('orders.priceType')"
                    @change="handleServiceOrPriceTypeChange">
                    <el-option :label="$t('orders.slow')" value="1" />
                    <el-option :label="$t('orders.medium')" value="2" />
                    <el-option :label="$t('orders.quick')" value="3" />
                    <el-option label="超快速" value="4" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>

            <div class="drawer-header">
              <div class="title">{{ $t('orders.certificationInfo') }}</div>
            </div>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item :label="$t('orders.certificationCompany')" prop="certificationCompany">
                  <el-select clearable v-model="addForm.certificationCompany"
                    :placeholder="$t('orders.certificationCompany')">
                    <el-option label="PSA" value="PSA" />
                    <el-option label="BGS" value="BGS" />
                    <el-option label="CGC" value="CGC" />
                    <el-option label="ARS" value="ARS" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="$t('orders.trainNumber')" prop="trainNumber">
                  <el-input v-model="addForm.trainNumber" :placeholder="$t('orders.trainNumber')" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="$t('orders.certificationStatus')" prop="certificationStatus">
                  <el-select clearable v-model="addForm.certificationStatus"
                    :placeholder="$t('orders.certificationStatus')">
                    <el-option v-for="dict in statusOptions" :key="dict.value" :label="dict.label"
                      :value="dict.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="$t('orders.certificationScore')" prop="certificationScore">
                  <el-input-number v-model="addForm.certificationScore" :min="0" :max="100" style="width: 100%;" />
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item :label="$t('orders.certificationNumber')" prop="certificationNumber">
                  <el-input v-model="addForm.certificationNumber" :placeholder="$t('orders.certificationNumber')" />
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item :label="$t('orders.psaUrl')" prop="psaUrl">
                  <el-input v-model="addForm.psaUrl" :placeholder="$t('orders.psaUrl')" />
                </el-form-item>
              </el-col>
            </el-row>
            <!-- 正面图片 -->
            <el-row>
              <el-col :span="12">
                <el-form-item :label="$t('orders.psaFontImgUrl')" prop="psaFontImgUrl">
                  <el-upload class="disassembly-uploader" :action="uploadUrl" :show-file-list="false"
                    :on-success="handleUploadSuccess2" :on-error="handleUploadError" :before-upload="beforeUpload">
                    <img v-if="addForm.psaFontImgUrl" :src="addForm.psaFontImgUrl" class="uploaded-image">
                    <i v-else class="el-icon-plus uploader-icon"></i>
                  </el-upload>

                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="$t('orders.psaBackImgUrl')" prop="psaBackImgUrl">
                  <el-upload class="disassembly-uploader" :action="uploadUrl" :show-file-list="false"
                    :on-success="handleUploadSuccess3" :on-error="handleUploadError" :before-upload="beforeUpload">
                    <img v-if="addForm.psaBackImgUrl" :src="addForm.psaBackImgUrl" class="uploaded-image">
                    <i v-else class="el-icon-plus uploader-icon"></i>
                  </el-upload>
                </el-form-item>

              </el-col>
            </el-row>

            <div class="drawer-header">
              <div class="title">{{ $t('orders.costInfo') }}</div>
            </div>
            <el-row :gutter="20">
              <el-col :span="12">
                <el-form-item :label="$t('orders.cost')" prop="cost">
                  <el-input v-model="addForm.cost" :placeholder="$t('orders.cost')" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="$t('orders.costStatus')" prop="costStatus">
                  <el-select clearable v-model="addForm.costStatus" :placeholder="$t('orders.costStatus')">
                    <el-option :label="$t('orders.addSubStatus3')" value="1" />
                    <el-option :label="$t('orders.addSubStatus4')" value="2" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="20">

              <el-col :span="12">
                <el-form-item :label="$t('orders.addSubMoney')" prop="addSubMoney">
                  <el-input v-model="addForm.addSubMoney" :placeholder="$t('orders.addSubMoney')" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item :label="$t('orders.addSubStatus')" prop="addSubStatus">
                  <el-select v-model="addForm.addSubStatus" clearable :placeholder="$t('orders.addSubStatus')">
                    <el-option :label="$t('orders.addSubStatus1')" value="1" />
                    <el-option :label="$t('orders.addSubStatus2')" value="2" />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="24">
                <el-form-item :label="$t('orders.remarks')" prop="remarks">
                  <el-input v-model="addForm.remarks" type="textarea" :placeholder="$t('orders.remarks')" />
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <div class="drawer-footer">
            <!-- <el-button @click="addDialogVisible = false" size="medium">{{ $t('common.cancel') }}</el-button> -->
            <!-- 暂存订单 -->
            <el-button type="primary" @click="submitAdd" size="medium">{{ $t('common.pause') }}</el-button>
            <el-button v-if="isEdit" @click="cancelEdit" size="medium">{{ $t('common.cancel') }}{{ $t('common.edit')
            }}</el-button>
          </div>
        </div>
        <div style="width: 50%;" class="right">
          <!-- 暂存订单列表 -->
          <div class="pause-header">
            <el-button type="primary" size="medium" :disabled="!pauseList.length" @click="handleSubmitAllPause">
              {{ $t('common.submitAllPauseOrders') }}
            </el-button>
            <div class="pause-count">共 {{ pauseList.length }} 条暂存订单</div>
          </div>
          <el-table :data="pauseList" style="width: 100%" border :header-cell-style="{
            background: '#f5f7fa',
            color: '#606266',
            fontWeight: 'bold'
          }" :row-class-name="tableRowClassName" highlight-current-row>
            <!-- index -->
            <el-table-column type="index" label="序号" width="80" align="center" />
            <!-- <el-table-column prop="orderCode" :label="$t('orders.orderCode')" width="150" align="center" /> -->
            <el-table-column prop="userEmail" :label="$t('orders.userEmail')" width="180" align="center" />
            <el-table-column prop="cardName" :label="$t('orders.cardName')" width="150" align="center" />
            <el-table-column prop="certificationCompany" :label="$t('orders.certificationCompany')" width="150"
              align="center" />
            <el-table-column prop="trainNumber" :label="$t('orders.trainNumber')" width="120" align="center" />
            <!-- <el-table-column prop="serviceType" :label="$t('orders.serviceType')" width="120" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.serviceType == 1">{{ $t('orders.certificationScore') }}</span>
                <span v-if="scope.row.serviceType == 2">{{ $t('orders.reCertification') }}</span>
                <span v-if="scope.row.serviceType == 3">{{ $t('orders.reSeal') }}</span>
              </template>
            </el-table-column> -->
            <el-table-column prop="certificationNumber" :label="$t('orders.certificationNumber')" width="120"
              align="center" />
            <el-table-column prop="psaFontImgUrl" :label="$t('orders.psaFontImgUrl')" width="120" align="center">
              <template slot-scope="scope">
                <el-image :src="scope.row.psaFontImgUrl" :fit="fit"></el-image>
              </template>
            </el-table-column>
            <!-- <el-form-item :label="$t('orders.certificationNumber')" prop="certificationNumber">
                  <el-input v-model="addForm.certificationNumber" :placeholder="$t('orders.certificationNumber')" />
                </el-form-item> -->
            <el-table-column label="操作" align="center" width="200" fixed="right">
              <template slot-scope="scope">
                <el-button size="mini" type="danger" @click="handleRemovePause(scope.$index)">{{ $t('common.delete')
                }}</el-button>
                <el-button size="mini" type="primary" @click="handleEditPause(scope.row)">{{ $t('common.edit')
                }}</el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>

    </el-drawer>

    <!-- 新增/编辑抽屉 -->
    <el-drawer :title="addDialogTitle" :visible.sync="addDialogVisible" direction="rtl" size="900px"
      :close-on-click-modal="false" custom-class="add-order-drawer">
      <div class="drawer-container">
        <div class="drawer-header">
          <div class="title">{{ $t('common.basicInfo') }}</div>
        </div>
        <el-form :model="addForm" ref="addFormRef" label-width="120px" :rules="addRules" class="add-form add-form-grid">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="$t('orders.orderCode')" prop="orderCode">
                <el-input v-model="addForm.orderCode" :placeholder="$t('orders.orderCode')" :disabled="isEdit" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('orders.userEmail')" prop="userEmail">
                <el-input v-model="addForm.userEmail" :placeholder="$t('orders.userEmail')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('orders.cardName')" prop="cardName">
                <el-input v-model="addForm.cardName" :placeholder="$t('orders.cardName')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('orders.serviceType')" prop="serviceType">
                <el-select clearable v-model="addForm.serviceType" :placeholder="$t('orders.serviceType')"
                  @change="handleServiceOrPriceTypeChange">
                  <el-option :label="$t('orders.certificationScore')" value="1" />
                  <el-option :label="$t('orders.reCertification')" value="2" />
                  <el-option :label="$t('orders.reSeal')" value="3" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('orders.priceType')" prop="priceType">
                <el-select clearable v-model="addForm.priceType" :placeholder="$t('orders.priceType')"
                  @change="handleServiceOrPriceTypeChange">
                  <el-option label="慢速" value="1" />
                  <el-option label="中速" value="2" />
                  <el-option label="快速" value="3" />
                  <el-option label="超快速" value="4" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <div class="drawer-header">
            <div class="title">{{ $t('orders.certificationInfo') }}</div>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="$t('orders.certificationCompany')" prop="certificationCompany">
                <el-select clearable v-model="addForm.certificationCompany"
                  :placeholder="$t('orders.certificationCompany')">
                  <el-option label="PSA" value="PSA" />
                  <el-option label="BGS" value="BGS" />
                  <el-option label="CGC" value="CGC" />
                  <el-option label="ARS" value="ARS" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('orders.trainNumber')" prop="trainNumber">
                <el-input v-model="addForm.trainNumber" :placeholder="$t('orders.trainNumber')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <!-- 送检状态 -->
              <el-form-item :label="$t('orders.certificationStatus')" prop="certificationStatus">
                <el-select clearable v-model="addForm.certificationStatus"
                  :placeholder="$t('orders.certificationStatus')">
                  <el-option v-for="dict in certificationStatusText" key="dict.value" :label="dict.label"
                    :value="dict.value" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('orders.certificationScore')" prop="certificationScore">
                <el-input-number v-model="addForm.certificationScore" :min="0" :max="100" style="width: 100%;" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item :label="$t('orders.certificationNumber')" prop="certificationNumber">
                <el-input v-model="addForm.certificationNumber" :placeholder="$t('orders.certificationNumber')" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item :label="$t('orders.psaUrl')" prop="psaUrl">
                <el-input v-model="addForm.psaUrl" :placeholder="$t('orders.psaUrl')" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
              <el-form-item :label="$t('orders.psaFontImgUrl')" prop="psaFontImgUrl">
                <el-upload class="disassembly-uploader" :action="uploadUrl" :show-file-list="false"
                  :on-success="handleUploadSuccess2" :on-error="handleUploadError" :before-upload="beforeUpload">
                  <img v-if="addForm.psaFontImgUrl" :src="addForm.psaFontImgUrl" class="uploaded-image">
                  <i v-else class="el-icon-plus uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('orders.psaBackImgUrl')" prop="psaBackImgUrl">
                <el-upload class="disassembly-uploader" :action="uploadUrl" :show-file-list="false"
                  :on-success="handleUploadSuccess3" :on-error="handleUploadError" :before-upload="beforeUpload">
                  <img v-if="addForm.psaBackImgUrl" :src="addForm.psaBackImgUrl" class="uploaded-image">
                  <i v-else class="el-icon-plus uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>

          <div class="drawer-header">
            <div class="title">{{ $t('orders.costInfo') }}</div>
          </div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="鉴定费用" prop="cost">
                <el-input v-model="addForm.cost" :placeholder="$t('orders.cost')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="贩卖金额" prop="saleAmount">
                <el-input v-model="addForm.saleAmount" :placeholder="$t('orders.saleAmount')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('orders.costStatus')" prop="costStatus">
                <el-select clearable v-model="addForm.costStatus" :placeholder="$t('orders.costStatus')">
                  <el-option :label="$t('orders.addSubStatus3')" :value="1" />
                  <el-option :label="$t('orders.addSubStatus4')" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item :label="$t('orders.addSubMoney')" prop="addSubMoney">
                <el-input v-model="addForm.addSubMoney" :placeholder="$t('orders.addSubMoney')" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item :label="$t('orders.addSubStatus')" prop="addSubStatus">
                <el-select clearable v-model="addForm.addSubStatus" :placeholder="$t('orders.addSubStatus')">
                  <el-option :label="$t('orders.addSubStatus1')" value="1" />
                  <el-option :label="$t('orders.addSubStatus2')" value="2" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="成本" prop="remarks">
                <el-input v-model="addForm.chengben" type="input" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item :label="$t('orders.remarks')" prop="remarks">
                <el-input v-model="addForm.remarks" type="textarea" :placeholder="$t('orders.remarks')" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <!-- removeBoxUrl -->
              <el-form-item label="委托拆壳图片" prop="remarks">
                <img style="width: 100px;height: 100px;" :src="addForm.removeBoxUrl" alt="">

              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="drawer-footer">
          <el-button @click="addDialogVisible = false" size="medium">{{ $t('common.cancel') }}</el-button>
          <!-- 确认新增 -->
          <el-button type="primary" @click="editOrder" size="medium">{{ $t('common.confirm') }}</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 详情抽屉 -->
    <el-drawer :title="$t('common.detail')" :visible.sync="drawer" direction="rtl" size="50%"
      custom-class="order-drawer">
      <div class="drawer-container">

        <div class="drawer-header">
          <div class="title">{{ $t('common.basicInfo') }}</div>
        </div>
        <el-descriptions :column="1" border class="drawer-descriptions" :label-style="{ width: '120px' }">
          <el-descriptions-item :label="$t('orders.orderCode')" label-class-name="description-label">
            <span class="description-content">{{ detail.orderCode }}</span>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('orders.userEmail')" label-class-name="description-label">
            <span class="description-content">{{ detail.userEmail }}</span>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('orders.userName')" label-class-name="description-label">
            <span class="description-content">{{ detail.userName }}</span>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('orders.cardName')" label-class-name="description-label">
            <span class="description-content">{{ detail.cardName }}</span>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('orders.serviceType')" label-class-name="description-label">
            <span class="description-content">{{ getServiceTypeLabel(detail.serviceType) }}</span>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('orders.priceType')" label-class-name="description-label">
            <span class="description-content">{{ getPriceTypeLabel(detail.priceType) }}</span>
          </el-descriptions-item>

        </el-descriptions>
        <!-- 详情弹出框 -->
        <div class="drawer-header">
          <div class="title">{{ $t('orders.certificationInfo') }}</div>
        </div>
        <el-descriptions :column="1" border class="drawer-descriptions" :label-style="{ width: '120px' }">
          <el-descriptions-item :label="$t('orders.certificationCompany')" label-class-name="description-label">
            <span class="description-content">{{ detail.certificationCompany }}</span>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('orders.trainNumber')" label-class-name="description-label">
            <span class="description-content">{{ detail.trainNumber }}</span>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('orders.certificationStatus')" label-class-name="description-label">
            <el-tag :type="getStatusType(detail.certificationStatus)" size="medium">
              {{ getStatusLabel(detail.certificationStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('orders.certificationScore')" label-class-name="description-label">
            <span class="description-content">{{ detail.certificationScore }}</span>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('orders.certificationNumber')" label-class-name="description-label">
            <span class="description-content">{{ detail.certificationNumber }}</span>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('orders.psaUrl')" label-class-name="description-label">
            <el-link v-if="detail.psaUrl" type="primary" :href="detail.psaUrl" target="_blank" :underline="false">
              {{ detail.psaUrl }}
            </el-link>
            <span v-else>-</span>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('orders.psaImgUrl')" label-class-name="description-label">
            <el-image
              style="max-width:200px;max-height:300px;width:200px;height:auto;border-radius:8px;box-shadow:0 2px 8px #eee;cursor:pointer;"
              :src="detail.psaImgUrl" :preview-src-list="[detail.psaImgUrl]" fit="contain" class="disassembly-image">
              <div slot="error" class="image-slot">
                <i class="el-icon-picture-outline"></i>
              </div>
            </el-image>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('orders.psaFontImgUrl')" label-class-name="description-label">
            <el-image
              style="max-width:200px;max-height:300px;width:200px;height:auto;border-radius:8px;box-shadow:0 2px 8px #eee;cursor:pointer;"
              :src="detail.psaFontImgUrl" :preview-src-list="[detail.psaFontImgUrl]" fit="contain"
              class="disassembly-image">
              <div slot="error" class="image-slot">
                未上传
              </div>
            </el-image>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('orders.psaBackImgUrl')" label-class-name="description-label">
            <el-image
              style="max-width:200px;max-height:300px;width:200px;height:auto;border-radius:8px;box-shadow:0 2px 8px #eee;cursor:pointer;"
              :src="detail.psaBackImgUrl" :preview-src-list="[detail.psaBackImgUrl]" fit="contain"
              class="disassembly-image">
              <div slot="error" class="image-slot">
                未上传
              </div>
            </el-image>
          </el-descriptions-item>
        </el-descriptions>

        <div class="drawer-header">
          <div class="title">{{ $t('orders.costInfo') }}</div>
        </div>
        <el-descriptions :column="1" border class="drawer-descriptions" :label-style="{ width: '120px' }">
          <el-descriptions-item :label="$t('orders.cost')" label-class-name="description-label">
            <span class="description-content price">{{ detail.cost }}</span>
          </el-descriptions-item>
          <!-- 费用状态 -->
          <el-descriptions-item :label="$t('orders.costStatus')" label-class-name="description-label">
            <span class="description-content">
              <!--已付  -->
              <span v-if="detail.costStatus == 1">{{ $t('orders.addSubStatus3') }}</span>
              <!-- 未付  -->
              <span v-if="detail.costStatus == 2">{{ $t('orders.addSubStatus4') }}</span>
            </span>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('orders.saleAmount')" label-class-name="description-label">
            <span class="description-content price">{{ detail.saleAmount }}</span>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('orders.addSubMoney')" label-class-name="description-label">
            <span class="description-content">{{ detail.addSubMoney }}</span>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('orders.addSubStatus')" label-class-name="description-label">
            <span class="description-content">{{ getAddSubStatusLabel(detail.addSubStatus) }}</span>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('orders.remarks')" label-class-name="description-label">
            <span class="description-content">{{ detail.remarks }}</span>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('common.updateDate')" label-class-name="description-label">
            <span class="description-content">{{ detail.updateDate }}</span>
          </el-descriptions-item>
          <el-descriptions-item :label="$t('common.createdTime')" label-class-name="description-label">
            <span class="description-content">{{ detail.createdTime }}</span>
          </el-descriptions-item>
        </el-descriptions>

        <div v-if="detail.removeBoxUrl" class="drawer-header">
          <div class="title">{{ $t('orders.removeBoxUrl') }}</div>
        </div>
        <div v-if="detail.removeBoxUrl" class="disassembly-image-container">
          <el-image :src="detail.removeBoxUrl" :preview-src-list="[detail.removeBoxUrl]" fit="contain"
            class="disassembly-image">
            <div slot="error" class="image-slot">
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </div>
      </div>
    </el-drawer>

    <!-- 价格配置弹窗 -->
    <el-dialog :title="$t('orders.priceConfig')" :visible.sync="priceConfigDialogVisible" width="800px"
      :close-on-click-modal="false">
      <el-tabs v-model="activeServiceType" type="card">
        <el-tab-pane :label="$t('orders.certificationScore')" name="1">
          <el-table :data="getFilteredPriceConfig('1')" border style="width: 100%" v-loading="priceConfigLoading"
            class="price-config-table" :row-class-name="priceConfigRowClassName"
            :span-method="(params) => priceConfigSpanMethod(params, '1')">
            <el-table-column prop="priceType" :label="$t('orders.priceType')" align="center">
              <template slot-scope="scope">
                {{ getPriceTypeLabel(scope.row.priceType) }}
              </template>
            </el-table-column>
            <el-table-column prop="coin" :label="$t('common.currency')" align="center">
              <template slot-scope="scope">
                {{ getCurrencyLabel(scope.row.coin) }}
              </template>
            </el-table-column>
            <el-table-column prop="price" :label="$t('common.price')" align="center" :class-name="'price-cell'" />
            <el-table-column prop="days" :label="$t('orders.days')" align="center" :class-name="'price-cell'" />
            <el-table-column :label="$t('common.operation')" align="center" width="100">
              <template slot-scope="scope">
                <el-button v-hasPermi="['order:price:edit']" size="mini" type="warning" icon="el-icon-edit"
                  @click="handleEditPriceConfig(scope.row)">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane :label="$t('orders.reCertification')" name="2">
          <el-table :data="getFilteredPriceConfig('2')" border style="width: 100%" v-loading="priceConfigLoading"
            class="price-config-table" :row-class-name="priceConfigRowClassName"
            :span-method="(params) => priceConfigSpanMethod(params, '2')">
            <el-table-column prop="priceType" :label="$t('orders.priceType')" align="center">
              <template slot-scope="scope">
                {{ getPriceTypeLabel(scope.row.priceType) }}
              </template>
            </el-table-column>
            <el-table-column prop="coin" :label="$t('common.currency')" align="center">
              <template slot-scope="scope">
                {{ getCurrencyLabel(scope.row.coin) }}
              </template>
            </el-table-column>
            <el-table-column prop="price" :label="$t('common.price')" align="center" :class-name="'price-cell'" />
            <el-table-column prop="days" :label="$t('orders.days')" align="center" :class-name="'price-cell'" />

            <el-table-column :label="$t('common.operation')" align="center" width="100">
              <template slot-scope="scope">
                <el-button v-hasPermi="['order:price:edit']" size="mini" type="warning" icon="el-icon-edit"
                  @click="handleEditPriceConfig(scope.row)">编辑</el-button>
              </template>
            </el-table-column> b
          </el-table>
        </el-tab-pane>

      </el-tabs>
      <div slot="footer" class="dialog-footer">
        <el-button @click="priceConfigDialogVisible = false">{{ $t('common.close') }}</el-button>
      </div>
    </el-dialog>

    <!-- 编辑价格配置弹窗 -->
    <el-dialog :title="$t('common.edit')" :visible.sync="editPriceDialogVisible" width="400px"
      :close-on-click-modal="false">
      <el-form :model="editPriceForm" label-width="100px">
        <el-form-item :label="$t('orders.serviceType')">
          <el-input v-model="editPriceForm.serviceTypeLabel" disabled />
        </el-form-item>
        <el-form-item :label="$t('orders.priceType')">
          <el-input v-model="editPriceForm.priceTypeLabel" disabled />
        </el-form-item>
        <el-form-item :label="$t('common.currency')">
          <el-select clearable v-model="editPriceForm.coin" :placeholder="$t('common.pleaseSelectCurrency')" disabled>
            <el-option :label="$t('common.cny')" value="1" />
            <el-option :label="$t('common.twd')" value="2" />
            <el-option :label="$t('common.jpy')" value="3" />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('orders.days')">
          <el-input v-model="editPriceForm.days" />
        </el-form-item>
        <el-form-item :label="$t('common.price')">
          <el-input v-model="editPriceForm.price" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editPriceDialogVisible = false">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="submitEditPriceConfig">{{ $t('common.confirm') }}</el-button>
      </div>
    </el-dialog>

    <!-- 委托拆壳图片上传弹窗 -->
    <el-dialog :title="$t('orders.removeBoxUrl')" :visible.sync="disassemblyDialogVisible" width="500px"
      :close-on-click-modal="false" custom-class="disassembly-dialog">
      <el-form :model="disassemblyForm" ref="disassemblyFormRef" label-width="100px">

        <template v-hasPermi="['order:removeBoxUrl:upload']">
          <el-form-item :label="$t('common.amount') + '(日元)'">
            <el-input-number v-model="disassemblyForm.removeBoxAmount" :min="0" :precision="2" :step="1" />
          </el-form-item>
        </template>

        <el-form-item :label="$t('common.uploadImage')" prop="imageUrl">
          <el-upload v-hasPermi="['order:removeBoxUrl:upload']" class="disassembly-uploader" :action="uploadUrl"
            :show-file-list="false" :on-success="handleUploadSuccess" :on-error="handleUploadError"
            :before-upload="beforeUpload">
            <img v-if="disassemblyForm.removeBoxUrl" :src="disassemblyForm.removeBoxUrl" class="uploaded-image">
            <i v-else class="el-icon-plus uploader-icon"></i>
          </el-upload>
          <span v-if="!myCheckPermi(['order:removeBoxUrl:upload'])">{{ $t('orders.uploadedByAdmin') }}</span>
          <!-- <div class="upload-tip">请上传拆壳后的图片，支持jpg、png格式</div> -->
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="disassemblyDialogVisible = false">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="submitDisassembly">{{ $t('common.confirm') }}</el-button>
      </div>
    </el-dialog>

    <!-- 委托贩卖弹窗 -->
    <el-dialog :title="$t('orders.certificationStatus4')" :visible.sync="delegatedSellDialogVisible" width="400px"
      :close-on-click-modal="false">
      <el-form :model="delegatedSellForm" ref="delegatedSellFormRef" label-width="100px">
        <!-- <el-form-item label="订单编号">
                    <span>{{ delegatedSellForm.orderCode }}</span>
                </el-form-item> -->
        <el-form-item :label="$t('common.amount') + '(日元)'" prop="saleAmount">
          <el-input-number v-model="delegatedSellForm.saleAmount" :min="0" :precision="2" :step="100"
            @change="calculateCommission" />
        </el-form-item>
        <el-form-item :label="$t('common.commission')">
          <span class="commission-amount">{{ commissionAmount }}</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="delegatedSellDialogVisible = false">{{ $t('common.cancel') }}</el-button>
        <el-button type="primary" @click="submitDelegatedSell">{{ $t('common.confirm') }}</el-button>
      </div>
    </el-dialog>

    <!-- 客户管理弹窗 -->
    <el-drawer :visible.sync="customerConfigDialogVisible" size="50%" :close-on-click-modal="false">
      <el-table :data="customerList">
        <!-- <el-table-column label="用户编号" align="center" key="userId" prop="userId"  /> -->
        <el-table-column label="用户账号" align="center" key="email" prop="email" :show-overflow-tooltip="true" />
        <el-table-column label="手机号码" align="center" key="phonenumber" prop="phonenumber" width="120" />
        <el-table-column label="寄送地址" align="center" key="address" prop="address" width="120" />
      </el-table>
    </el-drawer>
  </div>
</template>

<script>
import {
  listOrder, delOrder, addOrder,
  listPriceConfig, updatePriceConfig, getPrice, batchOrder, myCustom, shelf, exportExcle, shelfJinpai
} from '@/api/system/order'
import imgUpload from '@/components/ImageUpload/index.vue'
import { listUser, getUserProfile } from '@/api/system/user'
import { checkPermi } from '@/utils/permission.js'
import { OrderStatusText, certificationStatusText } from '@/utils/orderStatus.js'

export default {
  name: 'Orders',
  components: {
    imgUpload
  },
  data() {
    return {
      OrderStatusText,

      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 表格数据
      tableData: [],
      // 抽屉显示状态
      drawer: false,
      // 详情数据
      detail: {},
      // 新增弹窗显示状态
      addDialogVisible: false,
      // 新增表单数据
      addForm: {
        orderCode: '',
        userName: '',
        userEmail: '',
        cardName: '',
        serviceType: '',
        priceType: '',
        certificationCompany: '',
        trainNumber: '',
        certificationStatus: '',
        certificationScore: null,
        certificationNumber: '',
        psaUrl: '',
        cost: '',
        addSubMoney: '',
        addSubStatus: '',
        remarks: '',
        costStatus: '',
        chengben: '',
      },
      // 新增表单校验规则
      addRules: {},
      // 送鉴状态选项
      statusOptions: [
        { value: '1', label: this.$t('orders.certificationStatus1') },
        { value: '2', label: this.$t('orders.certificationStatus2') },
        { value: '3', label: this.$t('orders.certificationStatus3') },
        { value: '4', label: this.$t('orders.certificationStatus4') },
        { value: '5', label: this.$t('orders.certificationStatus5') },
        { value: '6', label: this.$t('orders.certificationStatus6') },
        { value: '7', label: this.$t('orders.certificationStatus7') },
        { value: '99', label: this.$t('orders.certificationStatus99') }
      ],

      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderCode: undefined,
        userName: undefined,
        userEmail: undefined,
        cardName: undefined,
        certificationCompany: undefined,
        trainNumber: undefined,
        certificationStatus: undefined,
        certificationScore: undefined,
        certificationNumber: undefined
      },
      addDialogTitle: '新增订单',
      isEdit: false,
      priceConfigDialogVisible: false,
      priceConfigList: [],
      priceConfigLoading: false,
      editPriceDialogVisible: false,
      editPriceForm: {
        id: '',
        serviceType: '',
        serviceTypeLabel: '',
        priceType: '',
        priceTypeLabel: '',
        price: '',
        coin: '1'
      },
      imgDialogVisible: false,
      activeServiceType: '1',
      disassemblyDialogVisible: false,
      disassemblyForm: {
        orderCode: '',
        imageUrl: '',
        remarks: '',
        id: ''
      },
      uploadUrl: process.env.VUE_APP_BASE_API + '/file/s3/upload', // 替换为实际的上传接口
      delegatedSellDialogVisible: false,
      delegatedSellForm: {
        orderCode: '',
        saleAmount: 0,
        id: ''
      },
      commissionAmount: '0.00',
      pauseList: [],
      pauseDialogVisible: false,
      pauseDialogTitle: '暂存订单',
      userList: [],
      customerConfigDialogVisible: false,
      customerList: []
    }
  },
  computed: {
    certificationStatusText() {
      return Object.entries(OrderStatusText).map(item => {
        return {
          value: item[0],
          label: item[1]
        }
      })
    }
  },
  created() {
    this.getList()
    this.getUserList()
  },
  methods: {
    exportExcle() {
      let obj = JSON.parse(JSON.stringify(this.queryParams))
      delete obj.pageNum
      delete obj.pageSize


      exportExcle(obj).then(res => {
        console.log(res.msg);
        let url = res.msg
        // 在新标签页中打开 URL
        window.open(url, '_blank');
      })
    },
    handleShangjia(row) {
      console.log(row);
      shelf(row.id).then(res => {
        this.$message.success('上架成功')
        this.getList()
        if (res.code === 200) {
          this.$message.success('上架成功')
        } else {
          this.$message.error(res.msg)
        }
      })

    },
    handleShangjianpai(row) {
      console.log(row);
      shelfJinpai(row.id).then(res => {
        this.$message.success('上架成功')
        this.getList()
        if (res.code === 200) {
          this.$message.success('上架成功')
        } else {
          this.$message.error(res.msg)
        }
      })
    },
    editOrder() {
      // 编辑订单
      console.log(this.addForm)
      // 调用编辑订单接口
      addOrder(this.addForm).then(res => {
        this.$message.success('编辑成功')
        this.getList()
        this.addDialogVisible = false
      }).catch(() => {
        this.$message.error('编辑失败')
      })
    },
    handleCustomerConfig() {
      this.customerConfigDialogVisible = true
      myCustom().then(res => {
        console.log(res.data);
        this.customerList = res.data
      })
    },
    myCheckPermi(value) {
      return checkPermi(value)
    },
    getUserList() {
      listUser({
        pageNum: 1,
        pageSize: 100000,
        userType: '01'
      }).then(res => {
        console.log(res);
        this.userList = res.rows.map(item => {
          return {
            value: item.email,
            label: item.email
          }
        })
      })
    },
    /** 查询订单列表 */
    getList() {
      this.loading = true
      listOrder(this.queryParams).then(response => {
        this.tableData = response.rows
        this.total = response.total
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm")
      this.handleQuery()
    },
    /** 重置表单 */
    resetForm(refName) {
      if (this.$refs[refName]) {
        this.$refs[refName].resetFields()
      }
    },
    /** 查看详情按钮操作 */
    handleDetail(row) {
      this.detail = row
      this.drawer = true
    },
    /** 关闭抽屉 */
    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done()
        })
        .catch(_ => { })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.addDialogTitle = '编辑订单'
      this.isEdit = true
      this.addDialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.addFormRef) {
          this.$refs.addFormRef.resetFields()
        }
        Object.assign(this.addForm, row)
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除该订单?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        delOrder(row.id).then(() => {
          this.$message.success('删除成功')
          this.getList()
        }).catch(() => {
          this.$message.error('删除失败')
        })
      }).catch(() => { })
    },
    // 表格行的样式
    tableRowClassName({ row, rowIndex }) {
      if (rowIndex % 2 === 0) {
        return 'even-row'
      }
      return 'odd-row'
    },
    // 获取状态标签类型
    getStatusType(status) {
      const statusMap = {
        '1': 'success',
        '2': 'warning',
        '3': 'info',
        '4': 'primary',
        '5': 'primary',
        '99': 'success'
      }
      return statusMap[status] || 'info'
    },
    // 获取送鉴状态中文名
    getStatusLabel(value) {
      const found = this.statusOptions.find(item => item.value == value)
      return found ? found.label : value
    },
    handleAdd() {
      getUserProfile().then(res => {
        console.log(res.data)
      })
      this.addDialogTitle = '新增订单'
      this.isEdit = false
      // this.addDialogVisible =
      this.pauseDialogVisible = true
      this.$nextTick(() => {
        if (this.$refs.addFormRef) {
          this.$refs.addFormRef.resetFields()
        }
      })
    },
    submitAdd() {
      // 检查订单编号是否重复
      const isDuplicate = this.pauseList.some(item =>
        item.uuid === this.addForm.uuid &&
        (!this.isEdit || item !== this.pauseList.find(p => p.uuid === this.addForm.uuid))
      );

      // if (isDuplicate) {
      //   this.$message.warning('订单编号已存在，请修改后重试');
      //   return;
      // }

      if (this.isEdit) {
        // 编辑模式：更新现有订单
        const index = this.pauseList.findIndex(item => item.uuid === this.addForm.uuid);
        if (index !== -1) {
          this.pauseList.splice(index, 1, JSON.parse(JSON.stringify(this.addForm)));
          this.$message.success('编辑成功');
        }
      } else {
        this.addForm.uuid = new Date().getTime()

        // 新增模式：添加新订单
        const formData = JSON.parse(JSON.stringify(this.addForm));
        this.pauseList.push(formData);
        this.$message.success('暂存成功');
      }

      // 重置表单和编辑状态
      // this.$refs.addFormRef.resetFields();
      this.isEdit = false;
      this.pauseDialogTitle = '暂存订单';
    },
    handlePriceConfig() {
      this.priceConfigDialogVisible = true
      this.priceConfigLoading = true
      listPriceConfig().then(res => {
        this.priceConfigList = res.data || []
        this.priceConfigLoading = false
      }).catch(() => {
        this.priceConfigLoading = false
      })
    },
    getServiceTypeLabel(val) {
      const map = {
        '1': '鉴定分数',
        '2': '重新鉴定',
        '3': '重新封壳'
      }
      return map[val] || val
    },
    getPriceTypeLabel(val) {
      const map = {
        '1': '慢速',
        '2': '中速',
        '3': '快速',
        '4': '超快速'
      }
      return map[val] || val
    },
    getCurrencyLabel(val) {
      const map = {
        '1': '人民币 (¥)',
        '2': '台币 (NT$)',
        '3': '日元 (¥)'
      }
      return map[val] || val
    },
    priceConfigRowClassName({ row, rowIndex }) {
      return rowIndex % 2 === 0 ? 'even-row' : 'odd-row';
    },
    priceConfigSpanMethod({ row, column, rowIndex }, serviceType) {
      if (column.property === 'priceType') {
        const list = this.getFilteredPriceConfig(serviceType).sort((a, b) => {
          return a.days - b.days
        })
        console.log(111)
        console.log(list)
        console.log(111)
        let prev = 0
        let count = 0
        for (let i = 0; i < list.length; i++) {
          if (i === 0 || list[i].priceType !== list[i - 1].priceType) {
            if (i > 0) {
              if (rowIndex >= prev && rowIndex < prev + count) {
                if (rowIndex === prev) {
                  return { rowspan: count, colspan: 1 }
                } else {
                  return { rowspan: 0, colspan: 0 }
                }
              }
            }
            prev = i
            count = 1
          } else {
            count++
          }
        }
        // 最后一组
        if (rowIndex >= prev && rowIndex < prev + count) {
          if (rowIndex === prev) {
            return { rowspan: count, colspan: 1 }
          } else {
            return { rowspan: 0, colspan: 0 }
          }
        }
      }
    },
    handleEditPriceConfig(row) {
      this.editPriceForm = {
        id: row.id,
        serviceType: row.serviceType,
        serviceTypeLabel: this.getServiceTypeLabel(row.serviceType),
        priceType: row.priceType,
        priceTypeLabel: this.getPriceTypeLabel(row.priceType),
        price: row.price,
        coin: row.coin,
        days: row.days
      }
      this.editPriceDialogVisible = true
    },
    submitEditPriceConfig() {
      updatePriceConfig(this.editPriceForm).then(() => {
        this.$message.success('编辑成功')
        this.editPriceDialogVisible = false
        this.handlePriceConfig()
      }).catch(() => {
        this.$message.error('编辑失败')
      })
    },
    handleServiceOrPriceTypeChange() {
      if (this.addForm.serviceType && this.addForm.priceType) {
        getPrice({
          serviceType: this.addForm.serviceType,
          priceType: this.addForm.priceType
        }).then(res => {
          if (res) {
            this.addForm.cost = res.msg
          }
        })
      }
    },
    getAddSubStatusLabel(val) {
      const map = {
        '1': '加收已付',
        '2': '加收未付'
      }
      return map[val] || val
    },
    getFilteredPriceConfig(serviceType) {
      return this.priceConfigList.filter(item => item.serviceType === serviceType)
    },
    handleDelegatedDisassembly(row) {
      this.disassemblyForm = {
        orderCode: row.orderCode,
        removeBoxUrl: '',
        remarks: '',
        id: row.id
      }
      this.disassemblyDialogVisible = true
    },
    handleUploadSuccess(response, file) {
      if (response.code === 200) {
        this.disassemblyForm.removeBoxUrl = response.data.url
        this.$forceUpdate()
        // this.$message.success('上传成功')
      } else {
        this.$message.error('上传失败')
      }
    },
    handleUploadSuccess1(response, file) {
      if (response.code === 200) {
        this.addForm.psaImgUrl = response.data.url
        this.$forceUpdate()
        // this.$message.success('上传成功')
      } else {
        this.$message.error('上传失败')
      }
    },
    handleUploadSuccess2(response, file) {
      if (response.code === 200) {
        this.addForm.psaFontImgUrl = response.data.url
        this.$forceUpdate()
        // this.$message.success('上传成功')
      } else {
        this.$message.error('上传失败')
      }
    },
    handleUploadSuccess3(response, file) {
      if (response.code === 200) {
        this.addForm.psaBackImgUrl = response.data.url
        this.$forceUpdate()
        // this.$message.success('上传成功')
      } else {
        this.$message.error('上传失败')
      }
    },

    handleUploadError() {
      this.$message.error('上传失败')
    },
    beforeUpload(file) {
      const isImage = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      // if (!isImage) {
      //     this.$message.error('只能上传jpg/png格式的图片!')
      //     return false
      // }
      // if (!isLt2M) {
      //     this.$message.error('图片大小不能超过 2MB!')
      //     return false
      // }
      return true
    },
    submitDisassembly() {
      // if (!this.disassemblyForm.removeBoxUrl) {
      //   this.$message.warning('请先上传图片')
      //   return
      // }

      // 更新订单状态为委托拆壳
      const updateData = {
        id: this.disassemblyForm.id,
        certificationStatus: '5', // 委托拆壳状态
        removeBoxUrl: this.disassemblyForm.removeBoxUrl,
        removeBoxAmount: this.disassemblyForm.removeBoxAmount
      }
      if (updateData.removeBoxUrl) {
        updateData.certificationStatus = '7'
      }

      addOrder(updateData).then(() => {
        this.$message.success('设置成功')
        this.disassemblyDialogVisible = false
        this.getList()
      }).catch(() => {
        this.$message.error('设置失败')
      })
    },
    handleReturnToCustomer(row) {
      this.$confirm('是否确认将该订单设置为已寄回客户状态?', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        const updateData = {
          id: row.id,
          certificationStatus: '3' // 已寄回客户状态
        }
        addOrder(updateData).then(() => {
          this.$message.success('设置成功')
          this.getList()
        }).catch(() => {
          this.$message.error('设置失败')
        })
      }).catch(() => { })
    },
    handleDelegatedSell(row) {
      this.delegatedSellForm = {
        orderCode: row.orderCode,
        saleAmount: 0,
        id: row.id
      }
      this.commissionAmount = '0.00'
      this.delegatedSellDialogVisible = true
    },
    calculateCommission() {
      const amount = this.delegatedSellForm.saleAmount || 0
      this.commissionAmount = (amount * 0.1).toFixed(2)
    },
    submitDelegatedSell() {
      if (!this.delegatedSellForm.saleAmount) {
        this.$message.warning('请输入金额')
        return
      }

      // 更新订单状态为委托贩卖
      const updateData = {
        id: this.delegatedSellForm.id,
        certificationStatus: '4', // 委托贩卖状态
        saleAmount: this.delegatedSellForm.saleAmount
      }

      addOrder(updateData).then(() => {
        this.$message.success('设置成功')
        this.delegatedSellDialogVisible = false
        this.getList()
      }).catch(() => {
        this.$message.error('设置失败')
      })
    },

    // 从暂存列表中移除
    handleRemovePause(index) {
      this.$confirm('是否确认删除该暂存订单?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.pauseList.splice(index, 1)
        this.$message.success('删除成功')
      }).catch(() => { })
    },
    handleSubmitAllPause() {
      this.$confirm('是否确认提交所有暂存订单?', "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(async () => {
        // 使用Promise.all处理所有提交请求
        // const promises = this.pauseList.map(order => batchOrder(order))
        const promises = await batchOrder(this.pauseList)
        console.log(promises)
        if (promises.code === 200) {
          this.$message.success('所有订单提交成功')
          this.pauseList = [] // 清空暂存列表
          this.getList() // 刷新主列表
        } else {
          this.$message.error('部分订单提交失败，请检查后重试')
        }
        // Promise.all(promises)
        //     .then(() => {
        //         this.$message.success('所有订单提交成功')
        //         this.pauseList = [] // 清空暂存列表
        //         this.getList() // 刷新主列表
        //     })
        //     .catch(() => {
        //         this.$message.error('部分订单提交失败，请检查后重试')
        //     })
      }).catch(() => { })
    },
    handleEditPause(row) {
      console.log(row);
      // 将选中的暂存订单数据填充到表单中
      this.addForm = JSON.parse(JSON.stringify(row));
      // 标记为编辑状态
      this.isEdit = true;
      // 更新标题
      this.pauseDialogTitle = this.$t('common.edit');
      // 打开抽屉
      this.pauseDialogVisible = true;
      // 等待 DOM 更新后重置表单验证状态
      this.$nextTick(() => {
        if (this.$refs.addFormRef) {
          this.$refs.addFormRef.clearValidate();
        }
      });
    },
    cancelEdit() {
      // 取消编辑，重置表单
      this.$refs.addFormRef.resetFields();
      this.addForm = {
        orderCode: '',
        userName: '',
        userEmail: '',
        cardName: '',
        serviceType: '',
        priceType: '',
        certificationCompany: '',
        trainNumber: '',
        certificationStatus: '',
        certificationScore: null,
        certificationNumber: '',
        psaUrl: '',
        cost: '',
        addSubMoney: '',
        addSubStatus: '',
        remarks: '',
        costStatus: ''
      };
      // 重置编辑状态
      this.isEdit = false;
      // 恢复标题
      this.pauseDialogTitle = '暂存订单';
      // 提示用户
      this.$message.info('已取消编辑');
    }
  }
}
</script>

<style scoped lang="scss">
.order-container {
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

/* 表格行样式 */
:deep(.even-row) {
  background-color: #fafafa;
}

:deep(.odd-row) {
  background-color: #ffffff;
}

:deep(.el-table__row:hover) {
  background-color: #f5f7fa !important;
}

:deep(.el-table__row.current-row) {
  background-color: #ecf5ff !important;
}

/* 抽屉样式 */
:deep(.order-drawer) {
  background-color: #f5f7fa;
}

:deep(.order-drawer .el-drawer__header) {
  margin-bottom: 0;
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
  color: #303133;
  font-size: 18px;
  font-weight: 500;
}

.drawer-container {
  padding: 20px;
}

.drawer-header {
  margin: 16px 0 12px;
}

.drawer-header .title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  border-left: 4px solid #409EFF;
  padding-left: 8px;
  display: inline-block;
}

.drawer-descriptions {
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 4px;
}

:deep(.description-label) {
  width: 120px;
  background-color: #fafafa;
  font-weight: 500;
}

.description-content {
  color: #606266;
}

.description-content.price {
  color: #f56c6c;
  font-weight: 500;
}

:deep(.el-descriptions-item__label) {
  color: #606266;
}

:deep(.el-descriptions-item__content) {
  color: #303133;
}

.add-order-drawer {
  .drawer-container {
    padding: 20px;
    height: calc(100% - 120px);
    overflow-y: auto;
  }

  .drawer-header {
    margin: 16px 0 12px;

    .title {
      font-size: 16px;
      font-weight: 500;
      color: #303133;
      border-left: 4px solid #409EFF;
      padding-left: 8px;
      display: inline-block;
    }
  }

  .drawer-footer {
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 20px;
    background: #fff;
    text-align: center;
    border-top: 1px solid #e4e7ed;

    .el-button {
      min-width: 100px;
    }
  }

  .add-form {
    padding: 8px 0;

    :deep(.el-form-item) {
      margin-bottom: 18px;
    }

    :deep(.el-input),
    :deep(.el-input-number),
    :deep(.el-select) {
      width: 100%;
    }
  }
}

.price-config-table {
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 4px 18px 0 rgba(60, 60, 60, 0.12);
  background: #fff;
  margin-bottom: 10px;
}

:deep(.price-config-table .el-table__header th) {
  background: #f0f6ff;
  color: #333;
  font-weight: bold;
  font-size: 15px;
}

:deep(.price-config-table .el-table__row.even-row) {
  background: #f8fafc;
}

:deep(.price-config-table .el-table__row.odd-row) {
  background: #fff;
}

:deep(.price-config-table .el-table__row:hover) {
  background: #e6f7ff !important;
}

:deep(.price-config-table .el-table__cell.price-cell) {
  color: #f56c6c;
  font-weight: bold;
  font-size: 16px;
}

.img-preview-dialog .el-dialog__body {
  padding: 0;
  background: #000;
}

/* 委托拆壳弹窗样式 */
.disassembly-dialog :deep(.el-dialog__body) {
  padding: 20px 30px;
}

.disassembly-uploader {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 178px;
  height: 178px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.disassembly-uploader:hover {
  border-color: #409EFF;
}

.uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.uploaded-image {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: cover;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

/* 委托拆壳图片样式 */
.disassembly-image-container {
  background: #fff;
  padding: 20px;
  border-radius: 4px;
  text-align: center;
  width: 200px;
  margin: 0 auto;
}

.disassembly-image {
  width: 100%;
  height: auto;
  border-radius: 4px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.image-slot {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 200px;
  height: 150px;
  background: #f5f7fa;
  color: #909399;
  font-size: 30px;
}

.commission-amount {
  color: #f56c6c;
  font-size: 16px;
  font-weight: bold;
}

.pause-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding: 0 10px;
}

.pause-count {
  color: #606266;
  font-size: 14px;
}
</style>
